package urlResourceReader;

import java.awt.Rectangle;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.MalformedURLException;
import java.net.URL;

import javax.swing.JEditorPane;
import javax.swing.JFrame;
import javax.swing.JScrollPane;

public class UrlResourceReader
{
	private final OutputStream out;
	private final JEditorPane editorPane = new JEditorPane();
	private final JScrollPane pane = new JScrollPane(this.editorPane);
	private final JFrame frame = new JFrame ();
	
	
	private void setUpFrame ()
	{
		this.frame.add(this.pane);
		this.frame.pack();
		Rectangle r = frame.getBounds();
		this.frame.setBounds(r.x, r.y, 400, 800);
		this.editorPane.setEditable(false);
		this.frame.setVisible(true);
	}
	
	public void close()
	{
		this.frame.dispose();
	}
	
	public UrlResourceReader (OutputStream os)
	{
		this.out = os;
		this.pane.setVisible(true);
		this.setUpFrame();
	}
	
	public void getResource (String url) throws MalformedURLException
	{
		try
		{
			URL current = new URL(url);
			BufferedInputStream in = new BufferedInputStream(current.openStream());
			int b;
			
			while((b = in.read()) != -1)
			{
				out.write(b);
			}
			out.write('\n');
			in.close();
			this.editorPane.setPage(current);
		}
		catch (IOException e)
		{
			// TODO Auto-generated catch block
			System.err.println("failed to open URL stream");
		} 
		
	}

	
}
